package com.atguigu.gmall.realtime.common.util;

import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import static com.atguigu.gmall.realtime.common.constant.Constant.*;

/**
 * @author Felix
 * @date 2024/6/19
 * 从MySQL中读取数据的工具类
 */
public class JdbcUtil {
    //获取MySql连接
    public static Connection getMysqlConnection() throws ClassNotFoundException, SQLException {
        // 获取 jdbc 连接
        // 1. 加载驱动
        Class.forName(MYSQL_DRIVER);
        return DriverManager.getConnection(MYSQL_URL, MYSQL_USER_NAME, MYSQL_PASSWORD);
    }

    public static void closeConnection(Connection conn) throws SQLException {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }

    //通用的从MySQL表中查询数据的方法
    public static <T> List<T> queryList(Connection conn, Class<T> clz, String sql, boolean... isUnderLineToCamel) throws Exception {

        boolean defaultIsUToC = false;  // 默认不执行下划线转驼峰

        if (isUnderLineToCamel.length > 0) {
            defaultIsUToC = isUnderLineToCamel[0];
        }

        List<T> list = new ArrayList<>();
        //获取数据库操作对象
        PreparedStatement ps = conn.prepareStatement(sql);
        //执行SQL语句
        ResultSet rs = ps.executeQuery();
        ResultSetMetaData metaData = rs.getMetaData();
        //处理结果集
        while (rs.next()) {
            //定义一个对象，用于封装查询出来的一条记录
            T obj = clz.newInstance();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object columnValue = rs.getObject(i);
                if(defaultIsUToC){
                    columnName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,columnName);
                }
                BeanUtils.setProperty(obj,columnName,columnValue);
            }
            list.add(obj);
        }
        return list;
    }

}
